package com.course.app.biz;

import com.course.app.api.data.MarkDTO;
import com.course.app.api.data.MarkItemDTO;
import com.course.app.transformer.MarkTransformer;
import com.course.domain.model.ClassPlan;
import com.course.domain.model.Student;
import com.course.domain.model.TaskClass;
import com.course.domain.model.Teacher;
import com.course.domain.service.ClassService;
import com.course.domain.service.TaskService;
import com.course.domain.service.UserService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Created by Justin on 2017/5/19.
 */
@Component
public class MarkBiz {

    private final UserService userService;
    private final TaskService taskService;
    private final ClassService classService;

    public MarkBiz(UserService userService,
                   TaskService taskService,
                   ClassService classService) {
        this.userService = userService;
        this.taskService = taskService;
        this.classService = classService;
    }

    public MarkDTO findMarkByStudent(int studentId, Pageable pageable) {
        Student student = userService.loadStudent(studentId);
        int courseId = student.getCourseId();
        Page<ClassPlan> page = classService.PageMarkByStudentIdAndCourseId(studentId, courseId, pageable);
        List<ClassPlan> plans = page.getContent();
        List<Integer> taskIds = Lists.transform(plans, ClassPlan::getClassId);
        List<Integer> teacherIds = Lists.transform(plans, ClassPlan::getTeacherId);
        Map<Integer, TaskClass> taskMap = Maps.uniqueIndex(taskService.findClass(taskIds), TaskClass::getId);
        Map<Integer, Teacher> teacherMap = Maps.uniqueIndex(userService.findTeacher(teacherIds), Teacher::getId);
        List<MarkItemDTO> items = Lists.newArrayListWithCapacity(plans.size());
        for (ClassPlan classPlan : plans) {
            Teacher teacher = teacherMap.get(classPlan.getTeacherId());
            TaskClass task = taskMap.get(classPlan.getClassId());
            MarkItemDTO item = MarkTransformer.toItem(classPlan, teacher, task);
            items.add(item);
        }
        return MarkTransformer.toDTO(items, page);
    }
}
